/*
*Copyright 2021-2023 NERCIS
*
*Licensed under the Apache License, Version 2.0 (the "License");
*you may not use this file except in compliance with the License.
*You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*Unless required by applicable law or agreed to in writing, software
*distributed under the License is distributed on an "AS IS" BASIS,
*WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*See the License for the specific language governing permissions and
*limitations under the License.
*/

package cn.ac.nercis.pes.community.controller.evaluation.prepare;

import cn.ac.nercis.pes.common.constant.evaluation.AssessmentResult;
import cn.ac.nercis.pes.common.constant.evaluation.EvaluationModule;
import cn.ac.nercis.pes.common.constant.project.FinishState;
import cn.ac.nercis.pes.common.utils.ConvertUtils;
import cn.ac.nercis.pes.community.component.controls.PesComboBox;
import cn.ac.nercis.pes.community.component.dialog.MessageDialog;
import cn.ac.nercis.pes.community.component.dialog.MessageType;
import cn.ac.nercis.pes.community.controller.base.GlobalEventHandle;
import cn.ac.nercis.pes.community.controller.base.InitEvalDataLoad;
import cn.ac.nercis.pes.community.manager.RealTimeSaveManager;
import cn.ac.nercis.pes.community.utils.*;
import cn.ac.nercis.pes.community.views.evaluation.prepare.PrepareView;
import cn.ac.nercis.pes.model.dto.evaluation.content.LastEvaluationDTO;
import cn.ac.nercis.pes.service.evaluation.EvaluationContentService;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.DatePicker;
import javafx.scene.control.TextField;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.net.URL;
import java.util.Objects;
import java.util.ResourceBundle;
import java.util.concurrent.CompletableFuture;

/**
 * 前次测评情况管理控制器
 * @author zpy
 * @version 1.0.0
 */
@Slf4j
public class LastEvaluationController implements Initializable, GlobalEventHandle, InitEvalDataLoad {

    @FXML
    private StackPane page;
    @FXML
    private Button saveButton;
    @FXML
    private Button tmpSaveButton;

    @FXML
    private TextField countTxt;
    @FXML
    private VBox lastInfoBox;
    @FXML
    private DatePicker lastDateTxt;
    @FXML
    private TextField unitTxt;
    @FXML
    private PesComboBox conclusionCbx;
    @FXML
    private TextField scoreTxt;

    private final EvaluationContentService evaluationContentService;
    private final RealTimeSaveManager realTimeSaveManager = new RealTimeSaveManager(this::realTimeSave);
    private String currentSystemId;

    public LastEvaluationController() {
        this.evaluationContentService = SpringUtils.getBean(EvaluationContentService.class);
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        saveButton.setGraphic(IconUtils.getGlyph("save-button-icon","btn-icon"));
        tmpSaveButton.setGraphic(IconUtils.getGlyph("temp-save-button-icon","btn-icon"));
        initConclusionComboBox();
        lastInfoBox.managedProperty().bind(lastInfoBox.visibleProperty());
        GuiStore.applyQuickSave(this.page,this::onGlobalSave);
        realTimeSaveManager.listenerTextChange(this.countTxt);
        realTimeSaveManager.listenerDateChange(this.lastDateTxt);
        realTimeSaveManager.listenerComboBoxChange(this.conclusionCbx);
        this.countTxt.textProperty().addListener((observableValue, oldValue, newValue) -> {
            if(StringUtils.isBlank(newValue)){
                AppUtils.showMessageDialog("次数不允许为空",MessageType.WARN,this.page);
                this.countTxt.requestFocus();
                return;
            }
            int count = ConvertUtils.toInteger(this.countTxt.getText());
            if(count<1){
                AppUtils.showMessageDialog("次数必需为大于0的整数",MessageType.WARN,this.page);
                return;
            }
            initCount(count);
        });
    }

    @Override
    public void initializeData(String systemId){
        LogUtils.info(log, "初始化前次测评情况信息...");
        this.currentSystemId = systemId;
        this.loadContent();
    }

    @Override
    public void onGlobalSave() {
        LogUtils.info(log, "执行快捷保存操作...");
        saveData(false,false);
    }

    @FXML
    public void onTmpSave(){
        LogUtils.info(log, "执行暂存操作...");
        this.saveData(false,false);
    }

    @FXML
    public void onFinishSave(){
        LogUtils.info(log, "执行保存操作...");
        this.saveData(false,true);
    }

    public void realTimeSave(){
        LogUtils.info(log, "执行即时保存操作...");
        this.saveData(true,false);
    }

    private void saveData(boolean realTime,boolean finish){
        if (StringUtils.isBlank(this.countTxt.getText())) {
            AppUtils.showMessageDialog("次数不允许为空", MessageType.WARN, this.page);
            this.countTxt.requestFocus();
            return;
        }
        int count = ConvertUtils.toInteger(this.countTxt.getText());
        if (count < 1) {
            AppUtils.showMessageDialog("次数必需为大于0的整数", MessageType.WARN, this.page);
            return;
        }
        if (count > 1 && !this.validContent()) {
            return;
        }
        LastEvaluationDTO lastEvaluation = LastEvaluationDTO.builder()
                .count(count)
                .notFirst(count > 1)
                .build();
        if (lastEvaluation.getNotFirst()) {
            lastEvaluation.setLastDate(this.lastDateTxt.getValue());
            lastEvaluation.setConclusion(this.conclusionCbx.getValue());
            lastEvaluation.setUnit(this.unitTxt.getText());
            lastEvaluation.setScore(this.scoreTxt.getText());
        }
        LogUtils.info(log, "保存前次测评情况信息...");
        LogUtils.record(log, "请求数据，systemId:{},data:{}", this.currentSystemId, lastEvaluation);
        CompletableFuture.supplyAsync(() -> this.evaluationContentService
                        .saveLastEvaluation( this.currentSystemId, lastEvaluation))
                .thenAccept(res -> Platform.runLater(() -> {
                    if (res.isSuccess()) {
                        refreshFinishProcess(finish);
                        if(!realTime){
                            AppUtils.showMessageDialog("保存成功",MessageType.SUCCESS,this.page);
                        }
                    } else {
                        if(realTime){
                            log.error("即时保存前次测评情况信息失败：{}",res.getMsg());
                        }else{
                            AppUtils.showMessageDialog(res.getMsg(),MessageType.FAIL,this.page);
                        }
                    }
                }))
                .exceptionally((ex) -> {
                    log.error("保存前次测评情况信息出错!", ex);
                    return null;
                });
    }

    private void initConclusionComboBox(){
        conclusionCbx.getItems().clear();
        for(AssessmentResult result : AssessmentResult.values()){
            conclusionCbx.getItems().add(result.getName());
        }
    }

    private void loadContent() {
        LogUtils.info(log, "获取前次测评情况信息...");
        LogUtils.info(log, "请求数据：{}", this.currentSystemId);
        CompletableFuture.supplyAsync(() -> this.evaluationContentService.findLastEvaluation(this.currentSystemId))
                .thenAccept(res -> Platform.runLater(() -> {
                    countTxt.setText(String.valueOf(res.getCount()));
                    if (res.getNotFirst()) {
                        lastDateTxt.setValue(res.getLastDate());
                        this.unitTxt.setText(res.getUnit());
                        this.conclusionCbx.getItems().stream()
                                .filter(s -> StringUtils.equals(s, res.getConclusion()))
                                .findFirst()
                                .ifPresent(i -> conclusionCbx.getSelectionModel().select(i));
                        this.scoreTxt.setText(res.getScore());
                    } else {
                        this.lastDateTxt.setValue(null);
                        this.unitTxt.setText("");
                        this.conclusionCbx.getSelectionModel().clearSelection();
                        this.scoreTxt.setText("");
                    }
                    initCount(res.getCount());
                }))
                .exceptionally((ex) -> {
                    log.error("获取前次测评情况信息出错!", ex);
                    MessageDialog.builder()
                            .withContainer(this.page)
                            .withType(MessageType.FAIL).withMessage("加载前次测评情况信息失败！")
                            .build().show();
                    return null;
                });
    }

    private void initCount(Integer count){
        this.lastInfoBox.setVisible(count>1);
    }

    private void refreshFinishProcess(boolean finish){
        var prepareView = AppStore.getEvaluationView(this.currentSystemId, PrepareView.class);
        if(prepareView.getController() instanceof PrepareController controller){
            controller.setEvalProcess(EvaluationModule.LAST_EVALUATION, finish ? FinishState.FINISH:FinishState.INCOMPLETE);
        }
    }

    private boolean validContent(){
        int count = ConvertUtils.toInteger(this.countTxt.getText());
        if(count > 1){
            if(Objects.isNull(this.lastDateTxt.getValue())){
                this.lastDateTxt.requestFocus();
                MessageDialog.builder()
                        .withContainer(this.page)
                        .withType(MessageType.WARN).withMessage("上次评估时间不能为空")
                        .build().show();
                return false;
            }
            if(Objects.isNull(this.conclusionCbx.getValue())
                    || StringUtils.isBlank(this.conclusionCbx.getValue())){
                this.conclusionCbx.requestFocus();
                MessageDialog.builder()
                        .withContainer(this.page)
                        .withType(MessageType.WARN).withMessage("请选择评估结论")
                        .build().show();
                return false;
            }
        }
        return true;
    }
}